<template>
  <div id="functionPoint">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-input
          clearable
          placeholder="关键字查询"
          type="search"
          v-model="keywords"
          @search-click="search"
          @keyup="keyup"
        ></vxe-input>
        <vxe-button
          type="text"
          status="primary"
          icon="vxe-icon-refresh"
          content="刷新"
          @click="handleSearch"
        ></vxe-button>
        <vxe-button
          type="text"
          status="success"
          icon="vxe-icon-square-plus"
          content="新建"
          @click="handleAdd"
        ></vxe-button>
        <vxe-button
          type="text"
          icon="vxe-icon-save"
          content="保存"
          class="text-cyan"
          @click="saveList"
        ></vxe-button>
        <vxe-button
          type="text"
          status="danger"
          icon="vxe-icon-delete"
          content="删除"
          @click="handleDelete"
        ></vxe-button>
      </template>
    </vxe-toolbar>
    <div class="pointTable">
      <vxe-table
        ref="pointTable"
        v-loading="loading"
        border
        :loading="showLoading"
        :height="conHeight - 200 + 'px'"
        :data="pointList"
        :row-config="{ isCurrent: true, isHover: true }"
        :keyboard-config="{
          isArrow: true,
          isTab: true,
          isEdit: true
        }"
        :edit-config="{
          trigger: 'click',
          mode: 'cell',
          showIcon: false,
          showStatus: true
        }"
        :edit-rules="formRule"
        resizable
        show-overflow
        keep-source
      >
        <vxe-column type="checkbox" width="36" align="center"></vxe-column>
        <vxe-column type="seq" title="序号" width="60" align="center"></vxe-column>
        <vxe-column field="title" title="名称" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row, rowIndex, column }">
            <vxe-input
              v-model="row.title"
              type="text"
              @keydown.enter="enterEvent(row, rowIndex, column)"
            ></vxe-input>
          </template>
        </vxe-column>
        <vxe-column field="code" title="编号" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row, rowIndex, column }">
            <vxe-input
              v-model="row.code"
              type="text"
              @keydown.enter="enterEvent(row, rowIndex, column)"
            ></vxe-input>
          </template>
        </vxe-column>
        <vxe-column
          field="describes"
          title="功能点描述"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
        >
          <template #edit="{ row, rowIndex, column }">
            <vxe-input
              v-model="row.describes"
              type="text"
              @keydown.enter="enterEvent(row, rowIndex, column)"
            ></vxe-input>
          </template>
        </vxe-column>
        <!-- <vxe-column field="url" title="图标" :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template #edit="{ row, rowIndex }">
            <VxePulldownSelectIconfont
              @ConfirmByClick="(data) => ConfirmByClick(data, row, 'iconPath', rowIndex, column)"
            />
          </template>
        </vxe-column> -->
      </vxe-table>
      <!-- <vxe-pager
        v-model:current-page="page.currentPage"
        v-model:page-size="page.pageSize"
        :total="page.totalResult"
        @page-change="pageChange"
        :layouts="[
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'Sizes',
          'FullJump',
          'Total'
        ]"
      >
      </vxe-pager> -->
    </div>
    <el-dialog v-model="showDialog" :title="formTitle" width="500px">
      <el-form
        ref="userForm"
        :model="form"
        :rules="formRule"
        label-width="100px"
        class="form-input-m"
        :inline-message="true"
      >
        <el-form-item prop="title" label="名称">
          <el-input type="text" v-model="form.title" placeholder="请输入名称" clearable></el-input>
        </el-form-item>
        <el-form-item prop="code" label="编号">
          <el-input type="text" v-model="form.code" placeholder="请输入编号" clearable></el-input>
        </el-form-item>
        <el-form-item prop="url" label="图标">
          <el-input type="text" v-model="form.url" placeholder="请输入图标" clearable></el-input>
        </el-form-item>
        <el-form-item prop="describes" label="功能点描述">
          <vxe-textarea v-model="form.describes" placeholder="默认尺寸"></vxe-textarea>
        </el-form-item>
        <el-form-item label="模块id">
          <el-input
            type="text"
            v-model="clickmoduleId"
            placeholder="请输入菜单id"
            clearable
          ></el-input>
        </el-form-item>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveHandler('userForm')">保存</el-button>
          <el-button @click="closeDialog('userForm')"> 取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance, watch } from 'vue';
let { proxy }: any = getCurrentInstance();
import { Splitpanes, Pane } from 'splitpanes';
import { ElMessage } from 'element-plus';
import { pageSizes } from '@/utils/common';
import { VXETable } from 'vxe-table';
import { IsEmpty } from '../../../utils/common';
import { AppStore } from '../../../stores/store';
let store = AppStore();
//暴露属性和方法
defineExpose({
  initPage
});

// 获取模块id
const moduleId = localStorage.getItem('moduleId');
let modulePointMap = store.userInfo.modulePointMap;
// 功能点权限
let modulePoitPre = reactive([]);
// 通过权限获取功能点
function getModulePointMap() {
  if (Object.keys(modulePointMap).includes(moduleId)) {
    modulePoitPre.push(...modulePointMap[moduleId]);
  }
}

// 模块id
let clickmoduleId = '';

// 分页
let page = reactive({
  currentPage: 1,
  pageSize: 10000,
  totalResult: 0
});
// 屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);
// 用户输入关键字
let keywords = ref('');
// 弹窗显示状态
let showDialog = ref(false);
// 弹窗表单标题
let formTitle = ref('新建功能点');

// 弹窗数据
let form = reactive({
  id: null,
  code: '', //编号
  title: '', //名称
  url: '', //图标地址
  describes: '', //功能点描述
  moduleId: '' //菜单id``
});

// 加载动画
let loading = ref(false);

// 表格数据
let pointList = reactive([]);

// 加载中 loading效果状态
let showLoading = ref(true);

// 表单规则
let formRule = reactive({
  code: [
    {
      required: true,
      message: '请输入编码',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到32个字符',
      trigger: 'blur'
    }
  ],
  title: [
    {
      required: true,
      message: '请输入名称',
      trigger: 'blur'
    }
  ]
});

onMounted(() => {
  // getPointList();
});
function initPage(moduleId) {
  clickmoduleId = moduleId;
  getPointList();
}

// 获取功能点数据
function getPointList() {
  let modulePageParam = {
    pageIndex: page.currentPage,
    pageSize: page.pageSize,
    moduleId: clickmoduleId
  };

  pointList.length = 0; //放入数据前清空数组
  proxy.$http.post('/api/sys/pointsPageList', modulePageParam).then((res) => {
    showLoading.value = false;
    console.log('功能点数据', res.data.modulePageList.records);
    page.totalResult = res.data.modulePageList.total;
    pointList.push(...res.data.modulePageList.records);
  });
}

// 点击删除
async function handleDelete() {
  let $Xtable = proxy.$refs.pointTable;
  let selectRows = $Xtable.getCheckboxRecords();
  if (selectRows.length > 1) {
    VXETable.modal.message({ content: '只能删除一条数据', status: 'warning' });
    return;
  }
  if (selectRows <= 0) {
    VXETable.modal.message({ content: '请选择要删除的', status: 'warning' });
    return;
  } else {
    const type = await VXETable.modal.confirm('您确定要删除吗？');
    if (type == 'cancel') {
      VXETable.modal.message({ content: `点击了${type == 'cancel' ? '取消' : '确定'}` });
    } else {
      proxy.$http
        .delete('/api/sys/deletePoints/' + selectRows[0].id)
        .then((res) => {
          VXETable.modal.message({ content: '删除成功', status: 'success' });
          getPointList();
        })
        .catch((err) => {
          VXETable.modal.message({ content: '删除异常', status: 'warning' });
        });
    }
  }
}

// 点击修改保存
function saveList() {
  // 获取表格实例
  let $Xtable = proxy.$refs.pointTable;

  if ($Xtable) {
    // 表格实例表用该方法拿到有id的
    const updateRecords = $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });
    console.log(updateRecords);

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e) => {
      let moduleAddParam = e;
      proxy.$http
        .post('/api/sys/editPoints', moduleAddParam)
        .then((res) => {
          VXETable.modal.message({ content: '修改成功', status: 'success' });
        })
        .catch((err) => {
          VXETable.modal.message({ content: '修改异常', status: 'error' });
        });
    });
    getPointList();
  } else {
    return;
  }
}
// 点击新增
function handleAdd() {
  console.log(clickmoduleId);
  showDialog.value = true;
  form.moduleId = clickmoduleId;
}

// 点击弹框保存
function saveHandler() {
  let $form = proxy.$refs.userForm;
  $form.validate((val) => {
    if (val) {
      proxy.$http
        .post('/api/sys/addPoints', form)
        .then((res) => {
          showDialog.value = false;
          VXETable.modal.message({ content: '新增成功', status: 'success' });

          getPointList();
          showDialog.value = false;
          $form.resetFields();
        })
        .catch((error) => {
          VXETable.modal.message({ content: '新增异常', status: 'error' });
        });
    } else {
      return;
    }
  });
}

// 点击刷新
function handleSearch() {
  getPointList();
}

//点击每页数量
function handleSizeChange(val) {
  page.pageSize = val;
  page.currentPage = 1;
  getPointList();
}

// 弹框取消
function closeDialog() {
  let $form = proxy.$refs.userForm;
  $form.resetFields();
  showDialog.value = false;
}

// 弹框关闭
function close() {
  let $form = proxy.$refs.userForm;
  $form.resetFields();
}
// 关键字搜索
function search() {
  pointList.length = 0;
  proxy.$http
    .post('/api/sys/pointsPageList', {
      keywords: keywords.value,
      menuId: clickmoduleId,
      pageIndex: 1,
      pageSize: 10
    })
    .then((res) => {
      pointList.push(...res.data.modulePageList.records);
    });
}
// 回车触发搜索关键字
function keyup(e) {
  if (e.$event.code == 'Enter') {
    search();
  }
}
// 点击下一页
function pageChange(val) {
  page.currentPage = val.currentPage;
  getPointList();
}

// 图标组件选中事件
function ConfirmByClick(data, row, fieldName, rowIndex = null, column = null) {
  if (IsEmpty(rowIndex) || IsEmpty(column)) {
    // console.log('rowIndex', rowIndex);
    // console.log('data', data);
    // console.log('模块数据', moduleList);
    // console.log('fieldName', fieldName);
    // console.log('row', row);
    pointList[rowIndex].icon = data;
    if (fieldName === 'iconPath' && IsEmpty(row.selectedIcon)) {
      proxy.form.selectedIconPath = data;
    }
  } else {
    pointList[rowIndex][fieldName] = data;
    if (fieldName === 'iconPath' && IsEmpty(row.icon)) {
      pointList[rowIndex].icon = data;
    }
  }
}
</script>
<style lang="scss">
#functionPoint {
  height: 100%;
  .pointTable {
    height: 95%;
  }
}
.dialog-footer {
  text-align: end;
}
</style>